'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { createPostTagGroup, removePostTagGroup } from '@/services/api';
import diff from 'microdiff';
import type { IDifference, IQueryPostDetails, ITagGroup } from '@/interfaces';
import useToast from '@/hooks/useToast';
import { clearFormData, getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdatePostTagGroup(
  this: any,
  {
    source,
    translatedFields,
  }: {
    source: IQueryPostDetails;
    translatedFields: PrefixedTTranslatedFields<'postAdminPage'>;
  },
) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    id: string;
    tagId: string;
  }>({
    id: '',
    tagId: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [currentRemoveItem, setCurrentRemoveItem] = useState<ITagGroup>();
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const createPostTagGroupMutation = useMutation(createPostTagGroup);
  const removePostTagGroupMutation = useMutation(removePostTagGroup);

  useEffect(() => {
    const diffData = diff(
      {
        id: '',
        tagId: '',
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();

      const data = getDiffData(differenceData);
      const id = data.id;
      const tagId = data.tagId;
      const postId = source.basic.id + '';
      await createPostTagGroupMutation.mutateAsync({
        id,
        data: {
          tagId,
          postId,
        },
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.saveCompleted,
      });
    } catch (e) {
      createPostTagGroupMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setForm(clearFormData(form));
      setDifferenceData([]);
      setCurrentRemoveItem(undefined);
    }
  }

  async function onClickRemove(item: ITagGroup) {
    try {
      if (!item.tags || !item.tags[0]) {
        show({
          type: 'DANGER',
          message: translatedFields.dataNotExists,
        });
        return;
      }

      setCurrentRemoveItem(item);

      const id = item.id;
      const tagId = item.tags[0].id + '';
      const postId = source.basic.id + '';
      await removePostTagGroupMutation.mutateAsync({
        id,
        data: {
          tagId,
          postId,
        },
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.deleteCompleted,
      });
    } catch (e) {
      removePostTagGroupMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setCurrentRemoveItem(undefined);
    }
  }

  function checkForm() {
    const { id, tagId } = form;

    if (!id) {
      throw translatedFields.tagGroupIdRequired;
    }

    if (!tagId) {
      throw translatedFields.tagIdRequired;
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLSelectElement | HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  return (
    <Box>
      <div className="vstack gap-4">
        {(source.tagGroups || []).length > 0 && (
          <div className="table-responsive">
            <table className="table table-hover align-middle">
              <thead>
                <tr className="text-nowrap">
                  <th scope="col" className="fw-normal">
                    标签组
                  </th>
                  <th scope="col" className="fw-normal">
                    标签
                  </th>
                  <th scope="col" className=""></th>
                </tr>
              </thead>
              <tbody>
                {(source.tagGroups || []).map((item) => {
                  return (
                    <tr key={item.id} className="text-nowrap">
                      <td>{`${item.name} (ID. ${item.id})`}</td>
                      <td>
                        {`${
                          item.tags && item.tags[0] && item.tags[0].name
                        } (ID. ${
                          item.tags && item.tags[0] && item.tags[0].id
                        })`}
                      </td>
                      <td>
                        <button
                          disabled={
                            currentRemoveItem &&
                            currentRemoveItem.id === item.id &&
                            removePostTagGroupMutation.isLoading
                          }
                          onClick={onClickRemove.bind(this, item)}
                          className="btn btn-sm btn-danger"
                          type="button"
                        >
                          {currentRemoveItem &&
                          currentRemoveItem.id === item.id &&
                          removePostTagGroupMutation.isLoading ? (
                            <Spinner classs="me-2" />
                          ) : (
                            <i className="bi bi-trash me-2"></i>
                          )}
                          {translatedFields.delete}
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        <form onSubmit={onClickSave} className="vstack gap-4">
          <div>
            <label className="form-label">{translatedFields.tagGroupId}</label>
            <input
              type="text"
              className="form-control"
              name="id"
              value={form.id}
              onChange={onChangeForm}
              aria-describedby="id"
              placeholder={translatedFields.tagGroupIdPlaceholder}
            />
          </div>

          <div>
            <label className="form-label">{translatedFields.tagId}</label>
            <input
              type="text"
              className="form-control"
              name="tagId"
              value={form.tagId}
              onChange={onChangeForm}
              aria-describedby="tagId"
              placeholder={translatedFields.tagIdPlaceholder}
            />
          </div>

          <button
            type="submit"
            disabled={createPostTagGroupMutation.isLoading || isDisabledSave}
            className="btn btn-success col col-lg-2 my-4"
          >
            {createPostTagGroupMutation.isLoading && <Spinner classs="me-2" />}
            {translatedFields.add}
          </button>
        </form>
      </div>
    </Box>
  );
}
